package leetCode;

import java.util.Scanner;

/*


3
3
9 9 4
6 6 8
2 1 1


 */

public class Solution329 {
    
    public int longestIncreasingPath(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] pathLength = new int[m][n];
        boolean[][] visited = new boolean[m][n];
        int maxPathLength = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                pathLength[i][j] = 1;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visited[i][j]) {
                    getLongestPath(i, j, matrix, visited, pathLength);
                }
                if (pathLength[i][j] > maxPathLength) {
                    maxPathLength = pathLength[i][j];
                }
            }
        }
        return maxPathLength;
    }

    private void getLongestPath(int i, int j, int[][] matrix, boolean[][] visited, int[][] pathLength) {
        int m = matrix.length;
        int n = matrix[0].length;
        int maxPathLength = 0;
        if (i - 1 >= 0 && matrix[i-1][j] > matrix[i][j]) {
            if (!visited[i-1][j]) {
                getLongestPath(i-1, j, matrix, visited, pathLength);
            }
            if (pathLength[i-1][j] > maxPathLength) {
                maxPathLength = pathLength[i-1][j];
            }
        }
        
        if (i + 1 < m && matrix[i+1][j] > matrix[i][j]) {
            if (!visited[i+1][j]) {
                getLongestPath(i+1, j, matrix, visited, pathLength);
            }
            if (pathLength[i+1][j] > maxPathLength) {
                maxPathLength = pathLength[i+1][j];
            }
        }
        if (j - 1 >= 0 && matrix[i][j-1] > matrix[i][j]) {
            if (!visited[i][j-1]) {
                getLongestPath(i, j-1, matrix, visited, pathLength);
            }
            if (pathLength[i][j-1] > maxPathLength) {
                maxPathLength = pathLength[i][j-1];
            }
        }
        if (j + 1 < n && matrix[i][j+1] > matrix[i][j]) {
            if (!visited[i][j+1]) {
                getLongestPath(i, j+1, matrix, visited, pathLength);
            }
            if (pathLength[i][j+1] > maxPathLength) {
                maxPathLength = pathLength[i][j+1];
            }
        }
        pathLength[i][j] += maxPathLength;
        visited[i][j] = true;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int m = scan.nextInt();
        int n = scan.nextInt();
        int[][] matrix = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = scan.nextInt();
            }
        }
        Solution329 s = new Solution329();
        System.out.println(s.longestIncreasingPath(matrix));
        scan.close();
    }

}